<?php
declare (strict_types = 1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Config;
use think\Request;
use think\admin\Controller;
use think\exception\HttpResponseException;
use think\facade\Session;
use think\facade\Cache;
use think\facade\Db;

use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Exchange\AMQPExchangeType;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Wire\AMQPTable;
use think\swoole\Websocket;
use app\index\service\ExcelService;
use app\index\service\ConfigService;

class Mq extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('mq')
            ->setDescription('the mq command');        
    }

    /*
    *  @desc      方法说明
    *  @author    saruri <saruri@163.com>
    *  @date      2020/08/01 18:05:35
    */
    public function conn()
    {
        //do somehing
        $this->MqConfig = Config::get('mq');
        
        //echo phpinfo();
        // exit();
       
        //halt($this->MqConfig);
        //exit('测试');
        //$this->ws = app('think\swoole\Websocket');
        $connection= new AMQPStreamConnection($this->MqConfig['ip'], $this->MqConfig['port'], $this->MqConfig['user'], $this->MqConfig['pwd'], $this->MqConfig['vhost']);
        //halt($this->MqConfig);
        return $connection;
    }

    protected function execute(Input $input, Output $output)
    {
    	//队列名  消息队列载体，每个消息都会被投入到一个或多个队列。
        $queue = 'hello';

        //建立连接
        $connection =self::conn();// new AMQPStreamConnection('127.0.0.1', 5672, 'saruri', 'sarurifanziping3389@', '/');
        //获取信道
        $channel = $connection->channel();
        //$this->ws = new Websocket('0.0.0.0');
        //声明创建队列
        $channel->queue_declare($queue, false, false, false, false);

        //消息消费
        $channel->basic_consume($queue, '', false, true, false, false, function ($msg) use ($output)  {

            $data=ExcelService::instance()->getExcelSql($msg->body);
            $output->writeln(time()." Received ==>" .$data.'<=='. $msg->body .  PHP_EOL);
            //$mqResult=$this->ws->to([1,2,3,4])->emit('testcallback', '队列消费了'.time());
           // P("执行了mq消费".time().$msg->body);
        });

        while (count($channel->callbacks)) {
            $channel->wait();
        }
		
        //关闭信道
        $channel->close();
        //关闭连接
        $connection->close();
		
    }

}

